#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""

@Time   :2025/7/28 下午10:24
@Author :zengjiahao1989@gmail.com
@File   :http.py
"""
import os

from flask import Flask
from flask_migrate import Migrate

from config import Config
from internal.exception import CustomException
from internal.router import Router
from pkg.response import json, Response, HttpCode
from pkg.sqlalchemy import SQLAlchemy


# from flask_sqlalchemy import SQLAlchemy


class Http(Flask):
    """Http服务引擎"""

    # *args 非命名的参数
    # **kwargs 命名参数
    def __init__(
            self,
            *args,
            conf: Config,
            db: SQLAlchemy,
            migrate: Migrate,
            router: Router,
            **kwargs
    ):
        super().__init__(*args, **kwargs)
        # 2.初始化应用配置 注册应用路由
        self.config.from_object(conf)

        # 3 注册绑定异常处理
        self.register_error_handler(Exception, self._register_error_handler)

        # 4 初始化flask扩展
        db.init_app(self)
        migrate.init_app(self, db, directory="internal/migration")
        # 2025-8-4注释这段代码，防止自动创建数据库，改为使用migrate
        # with self.app_context():
        #     # 这样写确保代码必定检索到App
        #     _ = App()
        #     db.create_all()

        # 5.注册应用路由,通过对象的方式把confp配置信息导入
        router.register_router(self)

    def _register_error_handler(self, error: Exception):
        # 1.异常信息是否自定义异常，若是提取message和code等信息
        if isinstance(error, CustomException):
            return json(Response(
                code=error.code,
                message=error.message,
                data=error.data if error.data is not None else "",
            ))
        # 2，若不是，则可能是程序或者数据库跑出的异常，提取信息，设置未FAIL状态码
        if self.debug or os.getenv("FLASK_ENV") == "development":
            raise error
        else:
            return json(Response(
                code=HttpCode.FAIL,
                message=str(error),
                data={}
            ))
        # print("异常:", error)
        # return error.message
